﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Douban.Api.Infrastructure;
using Douban.Api.Templates;
using Douban.Api.Web;

namespace Douban.Api.Broadcast
{
    public class BroadcastServiceProvider
    {
        private const string SendMiniblogUrl = "http://api.douban.com/miniblog/saying";

        public DoubanContext Context { get; set; }

        public MiniblogFeed GetMiniblogs(string userId, int startIndex, int maxResults)
        {
            return Context.GetProtectedResource<MiniblogFeed>(userId + "/miniblog", startIndex, maxResults);
        }

        public MiniblogFeed GetContactMiniblogs(string userId, int startIndex, int maxResults)
        {
            return Context.GetProtectedResource<MiniblogFeed>(userId + "/miniblog/contacts", startIndex, maxResults);
        }

        public Miniblog GetMiniblog(string miniblogId)
        {
            return Context.GetResource<Miniblog>(miniblogId, 0, 0);
        }

        public bool SendMiniblog(string content)
        {
            Template template = TemplateLoader.Instance.Load("Broadcast.SendMiniblog");
            template.Replace("content", content);

            AuthorizedResponse response = Context.SendResource(SendMiniblogUrl, template.ToString(), HttpMethods.Post);
            return response.StatusCode == System.Net.HttpStatusCode.Created;
        }

        public bool DeleteMiniblog(string miniblogId)
        {
            AuthorizedResponse response = Context.SendResource(miniblogId, "", HttpMethods.Delete);
            return response.StatusCode == System.Net.HttpStatusCode.OK;
        }

        /// <summary>
        /// Get saying's comments
        /// </summary>
        /// <param name="miniblogId">must be a saying's id</param>
        /// <returns></returns>
        public CommentFeed GetMiniblogComments(string miniblogId, int startIndex = 1, int maxResult = 50)
        {
            return Context.GetProtectedResource<CommentFeed>(miniblogId + "/comments", startIndex, maxResult);
        }

        /// <summary>
        /// Reply a saying
        /// </summary>
        /// <param name="miniblogId">must be a saying's id<</param>
        /// <param name="content"></param>
        /// <returns></returns>
        public bool ReplyMiniblog(string miniblogId, string content)
        {
            Template template = TemplateLoader.Instance.Load("Broadcast.ReplyMiniblog");
            template.Replace("content", content);

            AuthorizedResponse response = Context.SendResource(miniblogId + "/comments", template.ToString(), HttpMethods.Post);
            return response.StatusCode == System.Net.HttpStatusCode.Created;
        }
    }
}
